<?php

$stime = microtime(true);

include "ip.php";
include "useragent.php";

$ip = "";
$useragent = "";
$content = "";
$num =0;

for($i=0;$i<3;$i++)
{
	$num++;
	$ip = $ips[rand(0,(count($ips)-1))];
	$useragent = $useragents[rand(0,(count($useragents)-1))];
	if(empty($_REQUEST["order"])){
		$sort = "date";
	}
	else{
		$sort = "";
	}
	$result = getHtml($_REQUEST["term"],$_REQUEST["filter"],$sort,$_REQUEST["page"],$ip,$useragent,"");
	$content = $result["body"];

	if($content != "" && !strpos($content,"The document has moved"))
	{
		break;
	}
	else
	{
		@file_put_contents("result.txt",$ip."\r\n",FILE_APPEND);
	}
}

$result = array();
if(strpos($content,"Found 1 result for"))
{
	$result["type"] = 1;

	//标题
	preg_match("/<h1 class=\"heading-title\">(.+?)<\\/h1>/is",$content,$match);
	if($match){
		$result["title"] = trim($match[1]);
	}
	else{
		$result["title"] = "";
	}

	//短作者
	preg_match("/<div class=\"authors-list\">(.+?)<\\/div/is",$content,$match);
	if($match){
		$result["author"] = trim(str_replace("\n","",preg_replace("/<.+?>/is","",preg_replace("/<\\/.+?>/", "", $match[1]))));
	}
	else{
		$result["author"] = "";
	}
	//作者信息
	$result["authorinfo"] = "";
	preg_match_all("/<a class=\"full-name\".+?>(.+?)<\\/a>/is",$content,$matches);
	for($i = 0; $i < count($matches[1]); $i++)
	{
		$result["authorinfo"].= "<li>".$matches[1][$i]."</li>";
	}
	
	//关键词
	preg_match("/Keywords:(.+?)<\\/p>/is",$content,$match);
    if($match){
    	$result["keywords"] = trim(str_replace("\n","",preg_replace("/<.+?>/is","",preg_replace("/<\\/.+?>/", "", $match[1]))));
    }
    else{
        $result["keywords"] = "";
    }

    //简介
	preg_match("/<div class=\"abstract-content selected\".+?>(.+?)<\\/div>/is",$content,$match);
	if($match)
		$result["niabstract"] = preg_replace ( "/\s(?=\s)/","\\1", trim(str_replace("\n","",preg_replace("/<a.+?>/is","",preg_replace("/<\\/.+?>/", "", $match[1])))));
	else
		$result["niabstract"] = "";

	//文献信息
	preg_match("/<ul class=\"identifiers\" id=\"full-view-identifiers\">(.+?)<\\/ul>/is",$content,$match);
	if($match){
		$result["resc"] = preg_replace ( "/\s(?=\s)/","\\1", trim(str_replace("\n","",preg_replace("/<.+?>/is","",preg_replace("/<\\/.+?>/", "", $match[1])))));
	}
	else{
		$result["resc"] = "";
	}

	//图片
	preg_match("/<div class=\"nc_header\">(.+?)<\\/div><div class=\"morecit\">/",$content,$match);
	if($match){
		$result["pics"] = preg_replace("/src=\"/","src=\"http://ncproxy.yuntsg.com",str_replace("href=\"", "href=\"http://ncproxy.yuntsg.com", $match[1]));
	}
	else{
		$result["pics"] = "";
	}

	//引用
	preg_match("/<div class=\"morecit\">(.+?)<div id=\"comments_panel\"/",$content,$match);
	if($match){
		$result["morecit"] = "<div class=\"morecit\">".$match[1];
	}
	else{
		$result["morecit"] = "";
	}

}
else if(strpos($content,"log_resultcount")){
	$result["type"] = 2;

	//检索数量
	preg_match("/<meta name=\"log_resultcount\" content=\"(.+?)\"/",$content,$match);
	if($match){
		$result["num"] = $match[1];
	}
	else{
		$result["num"] = 0;
	}

	//修正检索词
	preg_match("/data-corrected-query=\"(.+?)\"/",$content,$match);
	if($match){
		$result["doyoumean"] = $match[1];
	}
	else{
		$result["doyoumean"] = "";
	}

	//检索式，废弃掉了
	$result["details"] = $_REQUEST["term"];

	//获取的右侧地址，废弃掉了
	$result["righturl"] = "";

	$list = array();
	preg_match_all("/<article class=\"labs-full-docsum\".+?>(.+?)<\\/article>/is",$content,$matches);
	for($i = 0; $i < count($matches[1]); $i++)
	{
		$html = $matches[1][$i];
		$html = str_replace("\r","",$html);
		$html = str_replace("\n","",$html);
		$html = preg_replace ( "/\s(?=\s)/","\\1", $html);

		$info = array();


		preg_match("/<a class=\"labs-docsum-title\".+?>(.+?)<\\/a>/",$html,$match);
		if($match){
			$info["title"] = $match[1];
		}
		else {
			$info["title"] = "";
		}

		preg_match("/<div class=\"full-view-snippet\">(.+?)<\\/div>/",$html,$match);
		if($match)
			$info["intro"] = $match[1];
		else
			$info["intro"] = "";

		preg_match("/<span class=\"labs-docsum-authors full-authors\">(.+?)<\\/span>/",$html,$match);
		if($match)
			$info["author"] = preg_replace("/<span.+?>/","",str_replace("</span>", "", $match[1]));
		else
			$info["author"] = "";

                preg_match("/<span class=\"labs-docsum-journal-citation full-journal-citation\">(.+?)<\\/span>/",$html,$match);
                if($match)
                        $info["source"] = preg_replace("/<span.+?>/","",str_replace("</span>", "", $match[1]));
                else
                        $info["source"] = "";
		
                preg_match("/<span class=\"docsum-pmid\">(.+?)<\\/span>/",$html,$match);
        	if($match){
	            $info["pmid"] = intval(str_replace("</b>","",str_replace("<b>","",$match[1])));
		}
		else
			$info["pmid"] = 0;

		$list[$i] = $info;			
	}
	$result["list"] = $list;
}
else
{
	$result["type"] = 0;
}

$etime = microtime(true);
$result["ipnum"]=$num;
$result["ip"] = $ip;
$result["cost"] = $etime - $stime;
echo json_encode($result);


function getHtml($term,$filter,$sort,$page,$ip,$useragent,$cookie)
{
        $cookie = "";
        $url = "https://pubmed.ncbi.nlm.nih.gov/?term=" . str_replace("%5C%27","%27",urlencode($term));
        if(!empty($filter)){
        	foreach (explode('ss,', $filter) as $value){
        		$url = $url."&filter=".$value;
        	}
        }

        if(!empty($sort)){
        	$url = $url . "&sort=".$sort;
        }

        if(!empty($page)){
        	$url = $url . "&page=".$page;
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION,0);
        curl_setopt($ch, CURLOPT_REFERER ,"https://pubmed.ncbi.nlm.nih.gov/");
        curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
        curl_setopt($ch, CURLOPT_TIMEOUT, 20);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if(!empty($ip)){
        	curl_setopt($ch, CURLOPT_INTERFACE, $ip);
        }
        if(!empty($cookie)){
        	curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        }

        $content = curl_exec($ch);
        preg_match("/location:(.+?)\r\n/i",$content,$match);
        if($match){
        	curl_setopt($ch, CURLOPT_URL, "https://pubmed.ncbi.nlm.nih.gov".trim($match[1]));
        	$content = curl_exec($ch);
		}
        curl_close($ch);
        list($header,$body) = explode("\r\n\r\n",$content);
        preg_match_all('/Set-Cookie: (.*);/isU',$header,$matches);
        $cookie = implode(";",$matches[1]);
        return array("body"=>$body,"cookie"=>$cookie);

}
?>
